// service.ts
interface Window {
  wst?: WebSocket;
  ws?: WebSocket;
}

class Service {
  private _wsImpl: typeof WebSocket | typeof window.MozWebSocket | null;
  
  constructor() {
    this._wsImpl = window.WebSocket || window.MozWebSocket || null;
  }

  private _CONNECT(data: any): void {
    if (this._wsImpl != null) {
      if (window.wst != null) return;
      console.log("connecting...");
      
      window.wst = new this._wsImpl('ws://127.0.0.1:36669/');
      
      window.wst.onmessage = (evt: MessageEvent) => {
        console.log("recv:" + evt.data);
        let rdata: any;
        try {
          rdata = JSON.parse(evt.data);
        } catch (e) {
          // Fallback to eval if JSON.parse fails
          rdata = eval("rdata=" + evt.data);
        }
        this._RECVMSG(rdata);
      };
      
      window.wst.onopen = () => {
        window.ws = window.wst;
        console.log("connected!!");
        if (data == null) return;
        this._SEND(data);
      };
      
      window.wst.onclose = () => {
        console.log("closed!!");
        const rdata: any = { tsCode: 'all', code: '-1', Message: '服务已关闭' };
        if (data != null) {
          rdata.tsCode = data.tsCode;
          rdata.Message = "服务未运行";
        }
        this._RECVMSG(rdata);
        delete window.wst;
      };
    }
  }

  private _RECVMSG(rdata: any): void {
    if (typeof showMsg === 'function') {
      showMsg(rdata);
    } else {
      console.warn('showMsg function is not defined');
    }
  }

  private _SEND(data: any): void {
    if (this._wsImpl == null) {
      return this._RECVMSG({ tsCode: data.tsCode, code: '-2', Message: '你的浏览器不支持Websocket' });
    }
    
    if (window.ws == null) {
      return this._CONNECT(data);
    }
    
    try {
      if (typeof showMsg === 'function') {
        showMsg("准备发送数据：" + JSON.stringify(data));
      }
      console.log("send:" + JSON.stringify(data));
      window.ws.send(JSON.stringify(data));
    } catch (e) {
      this._RECVMSG({ tsCode: data.tsCode, code: '-3', Message: '发送数据失败' });
    }
  }

  // 蜂鸣器
  beep(): void {
    this._SEND({ tsCode: "1001" });
  }

  // 读社保卡
  readSciCard(psamSlot?: string | number): void {
    const data: any = { tsCode: '1002' };
    if (psamSlot != null)
      data.psamSlot = "" + psamSlot;
    this._SEND(data);
  }

  // 读身份证
  readIDCard(picFilePath?: string): void {
    if (picFilePath == null) picFilePath = "d:\\zp.bmp";
    this._SEND({ tsCode: '1003', picFilePath: "" + picFilePath });
  }

  // 读身份证ID
  readIDCardUID(): void {
    this._SEND({ tsCode: '1004' });
  }

  // 读银行卡卡号
  readBankNO(): void {
    this._SEND({ tsCode: '1005' });
  }

  // 读M1卡
  readM1(addr: string | number, keyType: string | number, pwd: string | number): void {
    this._SEND({ 
      tsCode: '1006', 
      addr: "" + addr, 
      keyType: "" + keyType, 
      pwd: "" + pwd 
    });
  }

  // 验证社保卡PIN
  verifySciPIN(): void {
    this._SEND({ tsCode: '1007' });
  }

  // 修改社保卡PIN
  editSciPIN(): void {
    this._SEND({ tsCode: '1008' });
  }

  // 获取设备序列号
  getDeviceSN(): void {
    this._SEND({ tsCode: '1009' });
  }

  // 设置扫码模式
  setScanMode(mode: number): void {
    this._SEND({
      tsCode: '1011',
      mode: "" + mode  // mode： 1：主动 2：被动
    });
  }

  // 扫码  timeout：超时时间，单位：毫秒
  scan(timeout: number): void {
    this._SEND({
      tsCode: '1012',
      timeout: timeout // 超时时间，单位：秒
    });
  }
}

const service = new Service();

export { service as cardService};